/**
 * Base class for editing objects without version control
 */
Ext.define('app.editWindow',{
	   extend:'Ext.Window',
	   /**
	    * @property {Ext.form.Panel}
	    */
	   editForm:null,
	   /**
	    * @property {Ext.Button}
	    */
	   saveBtn:null,	  
	   /**
	    * @property integer
	    */
	   dataItemId:null,
	   /**
	    * @property {Ext.Toolbar.TextItem}
	    */
	   tbarText:false,
	   /**
	    * @property {app.historyPanel}
	    */
	   historyPanel:null,
	   /**
	    * @property string controllerUrl
	    */
	   controllerUrl:'',
	   objectName:'',
	   contentTabs:null,
	   linkedComponents:[],
	   canEdit:false,
	   canDelete:false,
	   contentTabs:null,

	   constructor: function(config) {
			config = Ext.apply({
				modal: true,
		        layout:'border',
		        width: app.checkWidth(config.width),
		        height:app.checkHeight(config.height),     
		        closeAction: 'destroy',
		        resizable:true,
		        items:[],
		        tbar:[],
		        fbar:[],
		        buttonsAlign:'right',
		        tools:app.windowToolsElements()
		    }, config);		
			
		this.callParent(arguments);		
	  },
	  /**
	   * Submit form
	   */
	  saveData: function()
	  {		  
		    var handle = this;
		    var form = this.editForm.getForm();
		    
		    var params = {};
		    
		    if(!Ext.isEmpty(this.linkedComponents)){
		    	Ext.each(this.linkedComponents , function(cmp){
		    		Ext.apply(params , cmp.collectData());
		    	});
		    }
		    
		 	form.submit({
				clientValidation: true,
				waitTitle:appLang.SAVING,
				method:'post',
				url:this.controllerUrl + 'edit',
				params:params,
				success: function(form, action) 
				{	
	   		 		if(!action.result.success){
	   		 			Ext.Msg.alert(appLang.MESSAGE, action.result.msg);
	   		 			return;
	   		 		} 
	   		 		  		 			
	 			    var dataId = action.result.data.id;
	 			   
	 				handle.editForm.getForm().findField('id').setValue(dataId);
	 				handle.historyPanel.setRecordId(dataId);
		 			handle.historyPanel.storeLoad();	
		 			
   		 			if(handle.canDelete){
	 			    	handle.deleteBtn.show();
	 			    }
   		 			
	 			    handle.fireEvent('dataSaved');
	   	        },
	   	        failure: app.formFailure
			});
	  },
	  /**
	   * Load form data
	   * @param integer itemId - record id
	   */
	  loadData: function(itemId)
	  {		
		  var handle = this;
		  
		  this.editForm.getForm().load({
			  waitMsg:appLang.LOADING,
			  url:this.controllerUrl + 'loaddata',
				method:'post',
			    params: {
			        'id':itemId
			    },
			    success: function(form, action) 
				{	
	   		 		if(action.result.success)
	   		 		{   	
			 			if(!Ext.isEmpty(handle.linkedComponents)){	 				
					    	Ext.each(handle.linkedComponents , function(cmp){
					    		cmp.setData(action.result.data[cmp.fieldName]);
					    	});
					    }			 		
			 			
			 			 //  History list
   		 			    handle.historyPanel.setRecordId(itemId);
   		 			    handle.historyPanel.storeLoad();	   	
			 			
   		 			    handle.fireEvent('dataLoaded' ,action.result);   	
	   		 		}
	   		 		else
	   		 		{
	   		 			Ext.Msg.alert(appLang.MESSAGE, action.result.msg);
	   		 			handle.close();
	   		 		}	
	   	        },
	   	        failure: app.formFailure
		  });
	  },	  
	  /**
	   * Delete record
	   */
	  deleteItem : function(){
		var handle = this;
		  Ext.Ajax.request({
 				url: this.controllerUrl + 'delete',
 				waitMsg:appLang.PROCESSING,
 				method: 'post',
 				params:{
 					'id':this.editForm.getForm().findField('id').getValue()
 				},
 		        success: function(response, request) {
 					response =  Ext.JSON.decode(response.responseText);
 					if(response.success){		  
 						handle.fireEvent('dataSaved');
 						handle.close();
 					}else{
 						Ext.MessageBox.alert(appLang.MESSAGE,response.msg);
 					}	
 		      }
 		 });
	  },
	  initComponent : function(){
		  	this.tbarText = new Ext.Toolbar.TextItem();

			this.deleteBtn = Ext.create('Ext.Button',{
				text:appLang.DELETE_ITEM,
				icon:'/i/system/delete.gif',
				hidden:true,
				listeners:{
					click:{
						fn: function(){this.deleteItem();},
						scope:this
					}
				}
			});
			
			var bar = [this.tbarText,'-'];
					
			if(this.canDelete){
				bar.push('->');
				bar.push(this.deleteBtn);
				this.deleteBtn.show();
			}
			
			this.historyPanel = new app.historyPanel({
				dataId:this.dataItemId,
				objectName:this.objectName,
				region:'center',				
				split:true,
				title:appLang.HISTORY,
				rowsOnPage:30
			});
			
			this.historyPanel.dataStore.proxy.extraParams['object'] = this.objectName;	
			
			this.rightPanel = new Ext.Panel({
				region:'east',
				collapsible:false,
				hidden:false,
				width:300,
				split:true,				
				layout:'border',
				items:[this.historyPanel],
				frame:false,
			    border:false
			});
			
		   this.tbar = bar;				
		   this.contentTabs = Ext.create('Ext.tab.Panel',{
			    plain:true,
				deferredRender:false,
				activeItem: 0, 
				enableTabScroll:true,
				border:false,
				frame:false,
				style:{
					backgroundColor:'#E5E4E2'
				},
				defaults:{
					border:false,
					frame:true,
			       	border:false,
			       	layout:'anchor',
			       	bodyPadding:'3px',
			       	fieldDefaults: {
			            labelAlign: 'right',
			            labelWidth: 160,
			            anchor: '100%'
			        }
				},
				items:[
				       {
							title:appLang.GENERAL,
							items:[
								{
									fieldLabel:"id",
									name:"id",
									xtype:"hidden"
								}
							]
						}
				]
		   });
		 
		   this.editForm = Ext.create('Ext.form.Panel', {
			    region:'center',
			    layout:'fit',
			    frame:false,
			    split:true,
			    items:[ this.contentTabs],
			    fieldDefaults: {
		            labelAlign: 'right',
		            labelWidth: 150,
		            anchor: '100%'
		        }
			});			

			this.saveBtn = new Ext.Button({
				text:appLang.SAVE,
				listeners:{
					click:{
						fn:function(){ this.saveData();},
						scope:this
					}
				}
			});
			
			this.items = [this.editForm, this.rightPanel];
		  
		    this.buttons = [];
		  
			if(this.canEdit){
				this.buttons.push(this.saveBtn);
			}

			this.buttons.push({
				text:appLang.CLOSE,
				listeners:{
					'click' : {
						fn:function(){
							this.close();
						},
						scope:this		
					}
				}
			});
		  this.callParent(arguments);
	      this.addEvents(
	            /**
	             * @event dataSaved
	             */
	           'dataSaved',
	            /**
	             * @event dataLoaded
	             * @param {object} result
	             */
	           'dataLoaded'
	       );  
	    },
	    /**
	     * Add linked component
	     * @param cmp
	     */
	    registerLink:function(cmp){
	    	this.linkedComponents.push(cmp);
	    }
});